package com.sam.nosql;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sam.data.UserData;
import com.snappydb.DB;
import com.snappydb.SnappydbException;


/**
 * A placeholder fragment containing a simple view.
 */
public class SnappyDBFragment extends Fragment implements View.OnClickListener {
    private Activity mActivity;
    private TextView mTvAdd;
    private DB mDB;
    private long time;
    public SnappyDBFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_snappy_db, container, false);
        mTvAdd = (TextView) view.findViewById(R.id.tv_add);
        mTvAdd.setOnClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
     /*   mActivity = getActivity();

        *//*
        DB snappyDB = new SnappyDB.Builder(context)
                    .directory(Environment.getExternalStorageDirectory().getAbsolutePath()) //optional
                    .name("books")//optional
                    .build();

       *//*
        try {
            mDB = DBFactory.open(mActivity);
        } catch (SnappydbException e) {
            e.printStackTrace();
        }*/
    }

    @Override
    public void onClick(View v) {
        if(mDB != null){
            try {
                time  = System.currentTimeMillis();
                optDb();
                time =System.currentTimeMillis() - time;
            } catch (SnappydbException e) {
                e.printStackTrace();
            }
        }

    }

    private void setUpTv(){
        StringBuilder sb = new StringBuilder();
        sb.append("time: ");
        sb.append(time);
        sb.append("\n");


    }
    public void optDb() throws SnappydbException {
        mDB.put("quote", "bazinga!");
        mDB.putShort("myshort", (short) 32768);
        mDB.putInt("max_int", Integer.MAX_VALUE);
        mDB.putLong("max_long", Long.MAX_VALUE);
        mDB.putDouble("max_double", Double.MAX_VALUE);
        mDB.putFloat("myfloat", 10.30f);
        mDB.putBoolean("myboolean", true);



        UserData userData = new UserData();
        userData.setName("张三");
        userData.setAge(33);
        userData.setHeight(133.33f);
        mDB.put("userData", userData);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mDB != null ){
            try {
                mDB.close();
                mDB.destroy();
            } catch (SnappydbException e) {
                e.printStackTrace();
            }
        }
    }
}
